// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/functions/prestosql/json/simd_json_extractor.h>

namespace kumo::pollux::functions {
    namespace {
        using JsonVector = std::vector<simdjson::ondemand::value>;
    }

    /* static */
    SIMDJsonExtractor &SIMDJsonExtractor::getInstance(
        melon::StringPiece path) {
        // Cache tokenize operations in JsonExtractor across invocations in the same
        // thread for the same JsonPath.
        thread_local static std::
                unordered_map<std::string, std::shared_ptr<SIMDJsonExtractor> >
                extractorCache;
        // Pre-process
        auto trimmedPath = melon::trimWhitespace(path).str();

        std::shared_ptr<SIMDJsonExtractor> op;
        if (extractorCache.count(trimmedPath)) {
            return *extractorCache.at(trimmedPath);
        }

        if (extractorCache.size() == kMaxCacheSize) {
            // TODO: Blindly evict the first one, use better policy
            extractorCache.erase(extractorCache.begin());
        }

        auto it =
                extractorCache.emplace(trimmedPath, new SIMDJsonExtractor(trimmedPath));
        return *it.first->second;
    }

    bool SIMDJsonExtractor::tokenize(const std::string &path) {
        thread_local static JsonPathTokenizer tokenizer;

        if (path.empty()) {
            return false;
        }

        if (!tokenizer.reset(path)) {
            return false;
        }

        while (tokenizer.hasNext()) {
            if (auto token = tokenizer.getNext()) {
                tokens_.emplace_back(token.value());
            } else {
                tokens_.clear();
                return false;
            }
        }

        return true;
    }

    simdjson::error_code extractObject(
        simdjson::ondemand::value &jsonValue,
        const std::string &key,
        std::optional<simdjson::ondemand::value> &ret) {
        SIMDJSON_ASSIGN_OR_RAISE(auto jsonObj, jsonValue.get_object());
        for (auto field: jsonObj) {
            SIMDJSON_ASSIGN_OR_RAISE(auto currentKey, field.unescaped_key());
            if (currentKey == key) {
                ret.emplace(field.value());
                return simdjson::SUCCESS;
            }
        }
        return simdjson::SUCCESS;
    }

    simdjson::error_code extractArray(
        simdjson::ondemand::value &jsonValue,
        const std::string &index,
        std::optional<simdjson::ondemand::value> &ret) {
        SIMDJSON_ASSIGN_OR_RAISE(auto jsonArray, jsonValue.get_array());
        auto rv = melon::tryTo<int32_t>(index);

        if (rv.hasValue()) {
            auto i = rv.value();
            if (i < 0) {
                size_t numElements;
                if (jsonArray.count_elements().get(numElements)) {
                    return simdjson::SUCCESS;
                }

                i += numElements;
            }
            auto val = jsonArray.at(i);
            if (!val.error()) {
                ret.emplace(std::move(val));
            }
        }
        return simdjson::SUCCESS;
    }
} // namespace kumo::pollux::functions
